package com.luckynote.common.base.serialize;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

/**
 * <pre>
 * *********************************************
 * Copyright LUCKY-NOTE.
 * All rights reserved.
 * ****************************************************
 *  Version       Date         Author            Desc
 *    v1.0       2019/6/29      bingo
 * ****************************************************
 * </pre>
 */
public class HessianSerializerUtil {

    private static final Logger logger = LoggerFactory.getLogger(HessianSerializerUtil.class);

    /**
     * 序列化对象，失败或异常返回null
     * @param source 待序列化的目标对象
     * @return 已序列化的字节码
     */
    public static byte[] serialize(Object source) {
        byte[] result = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        HessianOutput out = new HessianOutput(bos);
        out.setSerializerFactory(HessianSerializerFactory.SERIALIZER_FACTORY);
        try {
            out.writeObject(source);
            result = bos.toByteArray();
        } catch (Exception e) {
            logger.error("对象序列化失败", e);
        } finally {
            try {
                out.close();
                bos.close();
            } catch (Exception e) {
                logger.error("对象序化流关闭失败", e);
            }
        }

        return result;
    }

    /**
     * 反序列化对象，失败或异常返回null
     * @param source 已序列化的字节码
     * @param <T> 反序列化对象
     * @return 反序列化对象
     */
    @SuppressWarnings("unchecked")
    public static <T> T deSerialize(byte[] source) {
        T result = null;
        ByteArrayInputStream bin = new ByteArrayInputStream(source);
        HessianInput in = new HessianInput(bin);
        in.setSerializerFactory(HessianSerializerFactory.SERIALIZER_FACTORY);
        try {
            result = (T) in.readObject();
        } catch (Exception e) {
            logger.error("对象反序列化失败", e);
        } finally {
            try {
                bin.close();
                in.close();
            } catch (Exception e) {
                logger.error("对象序列化流关闭失败", e);
            }
        }
        return result;
    }
}
